﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Views.Grid;
using LSQL;
using DevExpress.XtraExport.Helpers;
using DevExpress.XtraEditors.Repository;
using DevExpress.CodeParser;
using DevExpress.XtraSpreadsheet.Import.OpenXml;
using Shopfloormanagement.Forms;
using DevExpress.XtraBars.Docking;

namespace Shopfloormanagement.Pre_Form
{
    public partial class sysSettings : DevExpress.XtraEditors.XtraForm
    {
        public static sysSettings instance = new sysSettings();
        public sysSettings()
        {
            instance = this;

            InitializeComponent();

        }
        private void sysSettings_Load(object sender, EventArgs e)
        {

            //gvUser.OptionsBehavior.EditingMode = DevExpress.XtraGrid.Views.Grid.GridEditingMode.EditForm; // 使用编辑表单
            //gvUser.OptionsEditForm.EditFormColumnCount = 1; // 编辑表单每行显示一个字段     
            GetAllDepartment();
            xtraTabControl1.ShowTabHeader = DevExpress.Utils.DefaultBoolean.False;
            cbUser.Properties.Items.Clear();
            DataTable dtUser = SQL.ReturnDataTableDist(SystemInfo.SQL, "ID,FullName", "Employees", $"Del_tag = 0");
            publicFunc.ComboBoxInit(dtUser, cbUser, "FullName", "ID");
            nodeTag = Convert.ToInt32(treeTeam.Nodes[0].Tag);
            LoadEmployeeDep(nodeTag);
        }
        public void GetAllDepartment()
        {
            treeTeam.Nodes.Clear(); // 清空旧节点
            DataTable dtTopLevel = LSQL.SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"Del_tag = 0 order by ID"); // 获取所有部门数据

            // 查找顶层节点（ParentDepartmentID 为 null 或 0）
            DataRow[] topLevelRows = dtTopLevel.Select($"departmentLevel = {publicFunc.MaxDepartmentLevel()}");

            foreach (DataRow row in topLevelRows)
            {
                TreeListNode parentNode = treeTeam.AppendNode(
                    new object[] { row["DepartmentName"] },
                    null
                );
                parentNode.Tag = row["ID"]; // 可选：存引用
                AddChildNodes(dtTopLevel, row, parentNode); // 递归添加子节点
            }
            treeTeam.OptionsBehavior.Editable = false;
            //treeTeam.ExpandAll(); // 全部展开
        }

        // 递归添加子节点
        private void AddChildNodes(DataTable dt, DataRow parentRow, TreeListNode parentNode)
        {
            int parentId = Convert.ToInt32(parentRow["ID"]);
            DataRow[] childRows = dt.Select($"ParentDepartmentID = {parentId}");

            foreach (DataRow row in childRows)
            {
                TreeListNode childNode = treeTeam.AppendNode(
                    new object[] { row["DepartmentName"] },
                    parentNode
                );
                childNode.Tag = row["ID"]; // 可选：存引用
                AddChildNodes(dt, row, childNode); // 递归
            }
        }

        private int nodeTag = -1;


        private void LoadEmployeeDep(int depID)
        {
            DataTable dtEmployee = SQL.ReturnDataTableDistinc(SystemInfo.SQL, "ID,EmployeeID,FullName,Scope", "View_EmployeeDepartments", $"DepartmentID = {depID}");
            gcUser.DataSource = dtEmployee;
            gvUser.Columns["ID"].Visible = false;
            gvUser.Columns["EmployeeID"].Visible = false;
            gvUser.Columns["FullName"].Caption = "Employee name";

            InitScopeUpdate();
        }

        private void treeTeam_FocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e)
        {
            if (e.Node != null && e.Node.Tag != null)
            {
                var tagValue = e.Node.Tag;
                //MessageBox.Show($"你点击的节点Tag是: {tagValue}");
                nodeTag = (int)tagValue;
                LoadEmployeeDep(nodeTag);
            }
        }

        private void gvUser_ShowingPopupEditForm(object sender, ShowingPopupEditFormEventArgs e)
        {
            // 设置编辑表单窗口位置为居中
            e.EditForm.StartPosition = FormStartPosition.CenterScreen;

            // 设置编辑表单的标题
            e.EditForm.Text = "修改权限";
        }


        private void InitScopeUpdate()
        {
            cbScope.Properties.Items.Clear();
            DataTable dtScopes = SQL.ReturnDataTable3(SystemInfo.SQL, "Scope", "Del_tag = 0 and ID != 4 order by ID desc");
            publicFunc.ComboBoxInit(dtScopes, cbScope, "Scope", "ID");
            var repositoryComboBox = new DevExpress.XtraEditors.Repository.RepositoryItemComboBox();
            for (int i = 0; i < dtScopes.Rows.Count; i++)
            {
                string scopeName = dtScopes.Rows[i]["Scope"].ToString();
                int scopeId = Convert.ToInt32(dtScopes.Rows[i]["ID"]);

                var item = new DevExpress.XtraEditors.Controls.ComboBoxItem(scopeName);
                item.Value = scopeId;
                repositoryComboBox.Items.Add(scopeName); // 只添加字符串

            }

            gcUser.RepositoryItems.Add(repositoryComboBox);

            // 绑定给 Scope 这一列
            gvUser.Columns["Scope"].ColumnEdit = repositoryComboBox;
        }

        private void gvUser_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int rowIndex = e.RowHandle;
            string selectText = gvUser.GetRowCellValue(rowIndex, "Scope").ToString();
            int ID = (int)gvUser.GetRowCellValue(rowIndex, "ID");
            DialogResult result = XtraMessageBox.Show(LookAndFeel, "是否保存？", "确认操作", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                gvUser.CloseEditor();  // 确保 GridView 结束编辑状态
                gvUser.UpdateCurrentRow();

                string selectedText = e.Value?.ToString();
                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "Scope", $"Scope = '{selectedText}'");
                int scopeId = (int)dt.Rows[0]["ID"];

                bool update = SQL.Update(SystemInfo.SQL, "EmployeeDepartments", $"Scope = '{scopeId}'", $"ID = {ID}");

                if (update)
                {
                    XtraMessageBox.Show("数据已成功保存！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    XtraMessageBox.Show("数据未保存！", "未保存", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }



            }
            else
            {

            }
        }

        private int userID = -1;
        private int scopeID = -1;
        private void cbUser_SelectedValueChanged(object sender, EventArgs e)
        {
            var selectedItem = cbUser.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                userID = Convert.ToInt32(tag);
            }
        }

        private void cbScope_SelectedValueChanged(object sender, EventArgs e)
        {
            var selectedItem = cbScope.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                scopeID = Convert.ToInt32(tag);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (publicFunc.GetUserScope(SystemInfo.userID, nodeTag) == false)
            {
                XtraMessageBox.Show(LookAndFeel, "You have no permission");
                return;
            }
            cbUser.Visible = true;
            cbScope.Visible = true;
            labelControl1.Visible = true;
            labelControl2.Visible = true;
            btnConfirm.Visible = true;
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (userID != -1 && scopeID != -1 && nodeTag != -1)
            {
                DataTable dtCheck = SQL.ReturnDataTableDist(SystemInfo.SQL, "EmployeeID", "EmployeeDepartments", $"EmployeeID = {userID} and DepartmentID = {nodeTag} and Del_tag = 0");
                if (dtCheck.Rows.Count > 0)
                {
                    XtraMessageBox.Show(LookAndFeel, "用户已存在！");
                    return;
                }
                else
                {
                    string col = "EmployeeID,DepartmentID,StartDate,Scope";
                    string value = $"{userID},{nodeTag},'{DateTime.Now.Date}',{scopeID}";
                    int res = SQL.InsertReturnID(SystemInfo.SQL, "EmployeeDepartments", col, value);
                    if (res > 0)
                    {
                        cbUser.Visible = false;
                        cbScope.Visible = false;
                        labelControl1.Visible = false;
                        labelControl2.Visible = false;
                        btnConfirm.Visible = false;
                        XtraMessageBox.Show("数据已成功保存！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        cbUser.SelectedIndex = -1;
                        cbScope.SelectedIndex = -1;

                        userID = -1;
                        scopeID = -1;
                        LoadEmployeeDep(nodeTag);
                        gcUser.RefreshDataSource();

                    }
                }
            }
        }

        private void btnInterfaceShow_Click(object sender, EventArgs e)
        {
            Form_Layout.instance.ShowDialog();
            Form_Layout.instance.StartPosition = FormStartPosition.CenterScreen;

        }

        private int gvUserID = -1;
        private void gvUser_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);
                if (hitInfo.InRow || hitInfo.InRowCell)
                {
                    popUser.ShowPopup(Control.MousePosition);
                    gvUserID = hitInfo.RowHandle;
                }
            }
        }

        private void popBtnDel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gvUserID != -1)
            {
                int ID = (int)gvUser.GetRowCellValue(gvUserID, "ID");

                bool res = SQL.Update(SystemInfo.SQL, "EmployeeDepartments", "Del_tag = 1", $"ID = {ID}");
                if (res)
                {
                    gvUserID = -1;
                    XtraMessageBox.Show("删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }

        }

        private int teamID = -1;
        private void treeTeam_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                TreeList treeList = sender as TreeList;
                TreeListHitInfo hitInfo = treeList.CalcHitInfo(e.Location);
                if (hitInfo.InRowCell || hitInfo.InRow)
                {
                    popTeam.ShowPopup(Control.MousePosition);
                    teamID = (int)hitInfo.Node.Tag;
                }

            }
            else if (e.Button == MouseButtons.Left)
            {
                TreeList treeList = sender as TreeList;
                TreeListHitInfo hitInfo = treeList.CalcHitInfo(e.Location);
                if (hitInfo.InRowCell || hitInfo.InRow)
                {
                    
                    teamID = (int)hitInfo.Node.Tag;
                }
            }

        }
        private void popBtnDepDel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (teamID != -1)
            {
                bool res = SQL.Update(SystemInfo.SQL, "Departments", "Del_tag = 1", $"ID = {teamID}");
                if (res)
                {
                    //说明部门删除成功
                    bool delRelation = SQL.Update(SystemInfo.SQL, "EmployeeDepartments", "Del_tag = 1", $"DepartmentID = {teamID}");
                    if (delRelation)
                    {
                        teamID = -1;
                        GetAllDepartment();
                        XtraMessageBox.Show("删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            MessageBox.Show(teamID.ToString());
            if (teamID != -1)
            {
                if (publicFunc.GetUserScope(SystemInfo.userID, teamID) == false)
                {
                    XtraMessageBox.Show(LookAndFeel, "You have no permission");
                    return;
                }
                teamAddForm.DepID = teamID;
                teamAddForm te = new teamAddForm();
                te.ShowDialog();
                GetAllDepartment();
            }
            else
            {
                if (publicFunc.GetUserSuper(SystemInfo.userID) == false)
                {
                    XtraMessageBox.Show(LookAndFeel, "You have no permission");
                    return;
                }
                teamAddForm te = new teamAddForm();
                te.ShowDialog();
                GetAllDepartment();
            }
            
        }

        private void btnDepRelation_Click(object sender, EventArgs e)
        {
            Relation_Load();
            xtraTabControl1.SelectedTabPageIndex = 1;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            
            xtraTabControl1.SelectedTabPageIndex = 0;
        }

        #region Dep relation
        private void Relation_Load()
        {
            UserScope();
        }

        private string ids = "";
        private void LoadDepartmentRelation()
        {
            if (selectDepID != -1)
            {
                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "View_DepRelation", $"mainDepID = {selectDepID}");
                gcDepRela.DataSource = dt;
                int[] idArray = new int[dt.Rows.Count];
                if (dt.Rows.Count > 0)
                {
                    for(int i = 0;i < dt.Rows.Count; i++)
                    {
                        idArray[i] = (int)dt.Rows[i]["DepID"];
                    }
                    ids = string.Join(",", idArray);
                }
                gvDepRela.Columns["mainDepID"].Visible = false;
                gvDepRela.Columns["mainDep"].Visible = false;
                gvDepRela.Columns["DepID"].Visible = false;
                gvDepRela.Columns["No."].Visible = false;

                gvDepRela.Columns["Department name"].Caption = "Res. Department";

            }
        }

        private void UserScope()
        {
            //查询用户的权限画像
            DataTable dtScope = SQL.ReturnDataTable3(SystemInfo.SQL,"View_EmployeeDepartments",$"EmployeeID = {SystemInfo.userID} and Scope = 'Manage'");
            
            if (dtScope.Rows.Count > 0)
            {
                publicFunc.ComboBoxInit(dtScope, cbMaster, "DepartmentName", "DepartmentID");
                publicFunc.ComboBoxInit(dtScope, cbResDep, "DepartmentName", "DepartmentID");
            }
        }
        

        private int selectDepID = -1;
        private void cbMaster_SelectedValueChanged(object sender, EventArgs e)
        {
            var selectedItem = cbMaster.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                selectDepID = Convert.ToInt32(tag);

                DataTable dt = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ID = {selectDepID}");
                int level = (int)dt.Rows[0]["departmentLevel"];
                LoadDepartmentRelation();
                if (ids.Length > 0)
                {
                    DataTable dtResDep = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ParentDepartmentID != {selectDepID} and departmentLevel <= {level} and ID != {selectDepID} and ID not in ({ids})");
                    publicFunc.ComboBoxInit(dtResDep, cbRes, "DepartmentName", "ID");
                }
                else
                {
                    DataTable dtResDep = SQL.ReturnDataTable3(SystemInfo.SQL, "Departments", $"ParentDepartmentID != {selectDepID} and departmentLevel <= {level} and ID != {selectDepID}");
                    publicFunc.ComboBoxInit(dtResDep, cbRes, "DepartmentName", "ID");
                }
                    
                
            }
        }

        private int selectResDepID = -1;
        private void cbRes_SelectedValueChanged(object sender, EventArgs e)
        {
            var selectedItem = cbRes.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                selectResDepID = Convert.ToInt32(tag);


            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            //写入！
            if (selectDepID != -1 && selectResDepID != -1)
            {
                bool isSQDC = chkSQDC.Checked;
                bool isDeviation = chkDeviation.Checked;

                string col = "mainDepID,DepID,isSQDC,isTopic";
                string value = $"{selectDepID},{selectResDepID},{Convert.ToInt32(isSQDC)},{Convert.ToInt32(isDeviation)}";
                int res = SQL.InsertReturnID(SystemInfo.SQL, "DepRelation", col, value);
                if (res > 0)
                {
                    XtraMessageBox.Show(LookAndFeel, $"成功添加{cbRes.Text}");
                    LoadDepartmentRelation();
                }
            }
        }

        private void LoadRequirment()
        {
            if (requirSelectID != -1)
            {
                DataTable dtRequir = SQL.ReturnDataTable3(SystemInfo.SQL, "View_DepRelation", $"DepID = {requirSelectID} and Confirmed = 0");
                gcRequir.DataSource = dtRequir;

                gvRequir.Columns["Department name"].Visible = false;
                gvRequir.Columns["Confirmed"].Visible = false;
                gvRequir.Columns["mainDepID"].Visible = false;
                gvRequir.Columns["DepID"].Visible = false;
                gvRequir.Columns["No."].Visible = false;

                gvRequir.Columns["mainDep"].OptionsColumn.AllowEdit = false;
                gvRequir.Columns["Visit SQDC"].OptionsColumn.AllowEdit = false;
                gvRequir.Columns["Visit issue"].OptionsColumn.AllowEdit = false;

                gvRequir.Columns["mainDep"].Caption = "Department name";
                gvRequir.Columns["Visit issue"].Caption = "Visit deviation";
            }
        }

        private int requirSelectID = -1;
        private void cbResDep_SelectedValueChanged(object sender, EventArgs e)
        {
            var selectedItem = cbResDep.SelectedItem as publicFunc.ComboBoxItem;
            if (selectedItem != null)
            {
                var tag = selectedItem.Tag; // 这里可以使用tag
                requirSelectID = Convert.ToInt32(tag);

                LoadRequirment();
            }
        }

        private int requirID = -1;
        private void gvRequir_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                // 获取鼠标点击的 GridView 位置
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.Location);

                if (hitInfo.InRow || hitInfo.InRowCell) // 确保右键点击在行内
                {
                    requirID = (int)gvRequir.GetRowCellValue(hitInfo.RowHandle, "No.");
                    popRequir.ShowPopup(Control.MousePosition); // 在鼠标位置显示菜单
                }
            }
        }

        private void barItemBtnConfirm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (requirID != -1)
            {
                bool confirm = SQL.Update(SystemInfo.SQL, "DepRelation", "isConfirm = 1", $"ID = {requirID}");
                if (confirm)
                {
                    XtraMessageBox.Show(LookAndFeel, "确认成功!");
                    requirID = -1;
                    LoadRequirment();
                }
            }
        }
        #endregion


    }
}